package example.linklist_array.合并有序;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

// https://leetcode-cn.com/problems/merge-two-sorted-lists/  合并两个有序链表
public class Demo2 {
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        }
        //todo 复用不来还是自己搭建单向链表
        ListNode head = null, tail = null;
        ListNode node111 = l1;
        ListNode node222 = l2;
        while (node111 != null && node222 != null) {
            if (node111.val < node222.val) {
                ListNode next = node111.next;
                ListNode node = new ListNode(node111.val);
                if (head == null) {
                    tail = node;
                    head = node;
                } else {
                    tail.next = node;
                    tail = node;
                }
                node111 = next;
            } else {
                ListNode next = node222.next;
                ListNode node = new ListNode(node222.val);
                if (head == null) {
                    tail = node;
                    head = node;
                } else {
                    tail.next = node;
                    tail = node;
                }
                node222 = next;
            }
        }
        if (node111 != null) {
            tail.next = node111;
        } else {
            tail.next = node222;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;
        ListNode node = mergeTwoLists(node1, node1);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
